package cc.vv.baselibrary.view;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.AppCompatEditText;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.MotionEvent;

import cc.vv.baselibrary.R;


/**
 * LKEditText
 * @author by CHP on 2017/3/6.
 */
public class LKEditText extends AppCompatEditText {
   private Context mContext;
    private Drawable rightDrawable;
    public LKEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext=context;

    }


    public LKEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext=context;
        initListener();
    }
    public void initListener(){
        rightDrawable = this.getCompoundDrawables()[2];
        rightDrawable= ContextCompat.getDrawable(mContext, R.mipmap.icon_clear);
        this.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if(s.length()>0){
                    LKEditText.this.setdrawableisvisible(true);
                }else{
                    setdrawableisvisible(false);
                }
            }
            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                          int arg3) {
            }

            @Override
            public void afterTextChanged(Editable arg0) {
                // TODO Auto-generated method stub

            }
        });
    }
    /**
     * 控制里面图片是否显示
     */
    public void setdrawableisvisible(boolean isVisible){
        //给四个方向设置图片的
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            this.setCompoundDrawablesRelativeWithIntrinsicBounds(null, null, isVisible?rightDrawable:null, null);
        }
    }
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if(event.getAction()== MotionEvent.ACTION_DOWN){
            float x=event.getX();
            if( x>this.getWidth()-(rightDrawable.getIntrinsicWidth()+this.getPaddingRight()) && x<this.getWidth()-this.getPaddingRight()){
                setText("");
            }
        }
        return super.onTouchEvent(event);
    }
}
